﻿using System;
using System.IO;
using System.Net;

namespace BitTorrent.Client.Peer.Message
{
    internal abstract class PeerMessage
    {
        public abstract byte[] GetMessage();

        protected static int ReadInt32(BinaryReader reader) {
            return IPAddress.NetworkToHostOrder(reader.ReadInt32());
        }

        protected static short ReadShort(BinaryReader reader) {
            return IPAddress.NetworkToHostOrder(reader.ReadInt16());
        }

        protected static byte[] ToBytes(int value) {
            return BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value));
        }

        protected static byte[] ToBytes(short value) {
            return BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value));
        }

        protected static byte[] GetMessageWithOnlyId(PeerMessageId peerMessageId) {
            var result = new byte[5];

            using (var memory = new MemoryStream(result)) {
                var writer = new BinaryWriter(memory);

                /// Length (fixed)
                writer.Write(ToBytes(1));
                writer.Write((byte)peerMessageId);

                writer.Flush();
            }

            return result;
        }

        protected static bool CheckStreamId(BinaryReader reader, PeerMessageId peerMessageId, bool peek) {
            if (peek) {
                return reader.PeekChar() == (byte)peerMessageId ? true : false;
            }
            return reader.ReadByte() == (byte)peerMessageId ? true : false;
        }
    }
}